<?php


namespace App\Admin\Services\AdminUser;


use App\Admin\Exceptions\Auth\UserException;
use App\Admin\Requests\AdminUser\UserCreateRequest;
use App\Admin\Requests\AdminUser\UserUpdatePasswordRequest;
use App\Admin\Requests\AdminUser\UserUpdateRequest;
use App\Repositories\AdminUser\UserRepository;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class AdminUserService {
    private $_repository;

    public function __construct(UserRepository $repository) {
        $this->_repository = $repository;
    }

    /**
     * 远程搜索用户列表
     *
     * @param Request $request
     * @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Builder[]|\Illuminate\Database\Eloquent\Collection|\Illuminate\Database\Eloquent\Model|\Illuminate\Database\Query\Builder|\Illuminate\Support\Collection|object|null
     */
    public function searchByQuery(Request $request) {
        return $this->_repository->getItemsByRemoteSearch(
            ['name' => $request->post('query')],
            [DB::raw('id as value'), DB::raw('name as label')]
        );
    }

    /**
     * 用户分页列表
     *
     * @return mixed
     */
    public function page() {
        return $this->_repository->queryByConditionAndPage();
    }

    /**
     * 新建用户
     *
     * @param UserCreateRequest $request
     * @return \Illuminate\Database\Eloquent\Model
     */
    public function store(UserCreateRequest $request) {
        $fillData = $request->post();
        $fillAble = $request->getRuleKeys();
        return $this->_repository->store($fillData, $fillAble);
    }

    /**
     * 删除用户
     *
     * @param $id
     * @return \Illuminate\Database\Eloquent\Model|mixed
     * @throws \Exception
     */
    public function delete($id) {
        return $this->_repository->delete($id, null, new UserException(1100005));
    }

    /**
     * 更新用户信息
     *
     * @param $id
     * @param UserUpdateRequest|UserUpdatePasswordRequest $request
     * @return \Illuminate\Database\Eloquent\Model|mixed
     * @throws \Exception
     */
    public function update($id, $request) {
        return $this->_repository->update($id, $request->post(), $request->getRuleKeys(), new UserException(1100005));
    }
}